package com.yuven.appframework.module

import android.text.TextUtils

abstract class BaseProxy<U,S>:IProxy<U,S> {
    var mProxy:BaseModule<U,S> ?=null

    override fun getUiInterface():U{
        return getProxy().getUiInterface()
    }

    override fun getServiceInterface():S{
        return getProxy().getServiceInterface()
    }
    abstract fun getModuleClassName():String
    abstract fun getDefaultModule():BaseModule<U,S>


    fun getProxy():BaseModule<U,S>{
        if(mProxy == null){
            var moduleClassName = getModuleClassName()
            if(!TextUtils.isEmpty(moduleClassName)){
                mProxy = try{
                    loadModule(moduleClassName,this.javaClass.classLoader) as BaseModule<U, S>
                }catch (e:Throwable) {
                    getDefaultModule()
                }
            }

        }
        return mProxy!!
    }

    @Throws(
        ClassNotFoundException::class,
        InstantiationException::class,
        IllegalAccessException::class
    )
    private  fun loadModule(
        className: String,
        classLoader: ClassLoader
    ): Any? {
        val aClass = Class.forName(className, false, classLoader)
        return aClass.newInstance()
    }

}